package com.qiniu.pili.droid.rtcstreaming.demo.paly;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.qiniu.pili.droid.rtcstreaming.RTCConferenceOptions;
import com.qiniu.pili.droid.rtcstreaming.RTCStartConferenceCallback;
import com.qiniu.pili.droid.rtcstreaming.RTCStreamingManager;
import com.qiniu.pili.droid.rtcstreaming.demo.R;
import com.qiniu.pili.droid.rtcstreaming.demo.test.AudioCapturer;
import com.qiniu.pili.droid.streaming.AVCodecType;
import com.qiniu.pili.droid.streaming.StreamingProfile;

import java.util.concurrent.atomic.AtomicBoolean;

public class AddConferenceActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mAddConference;
    private Button mQuitConference;
    private String userId = "Leo";
    private String roomId = "GID_MARSAR_CLOUD_153188254426124288";
    private String roomToken = "0xkNXdzEAVclERzD_DBlZknsmJRdJhVeCuDuKPdI:ic1IjRp0jM-D9Y8zvoty5S5Qt3E=:eyJyb29tX25hbWUiOiJHSURfTUFSU0FSX0NMT1VEXzE1MzE4ODI1NDQyNjEyNDI4OCIsInVzZXJfaWQiOiJHSURfTUFSU0FSX0NMT1VEXzE1MzE4ODI1NDQyNjEyNDI4OCIsInBlcm0iOiJhZG1pbiIsImV4cGlyZV9hdCI6MTUxNjc3NTgwNn0=";
    private RTCStreamingManager mRtcStreamingManager;
    private ProgressDialog mProgressDialog;
    private AudioCapturer mAudioCapturer;
    private StreamingProfile mStreamingProfile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_conference);
        RTCStreamingManager.init(getApplicationContext());
        mRtcStreamingManager = new RTCStreamingManager(this, AVCodecType.HW_VIDEO_YUV_AS_INPUT_WITH_HW_AUDIO_CODEC);
        initView();
        initConference();
        mProgressDialog = new ProgressDialog(this);
    }

    private void initConference() {
        //2.连麦参数设置
        RTCConferenceOptions options = new RTCConferenceOptions();
        options.setVideoEncodingSizeRatio(RTCConferenceOptions.VIDEO_ENCODING_SIZE_RATIO.RATIO_16_9);
        options.setVideoEncodingSizeLevel(RTCConferenceOptions.VIDEO_ENCODING_SIZE_HEIGHT_720);
        options.setVideoBitrateRange(300 * 1000, 800 * 1000);
        // 15 fps is enough
        options.setVideoEncodingFps(15);
        //3.主播配置推流参数
        mStreamingProfile = new StreamingProfile();
        mStreamingProfile
                .setVideoQuality(StreamingProfile.VIDEO_QUALITY_HIGH2)//视频流
                .setAudioQuality(StreamingProfile.AUDIO_QUALITY_HIGH1)
                .setEncoderRCMode(StreamingProfile.EncoderRCModes.QUALITY_PRIORITY)
                .setEncodingOrientation(StreamingProfile.ENCODING_ORIENTATION.PORT)
                .setPreferredVideoEncodingSize(1280, 720) // 配置推流的尺寸，建议与连麦尺寸一致
                .setYuvFilterMode(StreamingProfile.YuvFilterMode.Linear)
                .setBitrateAdjustMode(StreamingProfile.BitrateAdjustMode.Auto)
                .setFpsControllerEnable(true)
                .setVideoAdaptiveBitrateRange(300 * 1024 * 8, 800 * 1024 * 8)

        ;
        mRtcStreamingManager.setConferenceOptions(options);

        //5.prepare完成配置
        mRtcStreamingManager.prepare(mStreamingProfile);
    }

    private void initView() {
        mAddConference = (Button) findViewById(R.id.add_conference);
        mQuitConference = (Button) findViewById(R.id.quit_conference);

        mAddConference.setOnClickListener(this);
        mQuitConference.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_conference:
                mAudioCapturer = new AudioCapturer();
                mProgressDialog.setMessage("正在加入连麦。。。");
                mProgressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mAudioCapturer.startCapture();
                        startConferenceInternal();
                    }
                }).start();
                break;
            case R.id.quit_conference:
                if (mRtcStreamingManager.isConferenceStarted()) {
                    mRtcStreamingManager.stopConference();
                    Toast.makeText(this, "退出连麦", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void startPublishStreamingInternal() {

    }

    private void startConferenceInternal() {

        if (roomToken == null) {
//            dismissProgressDialog();
            showToast("无法获取房间信息 !");
        }

        try {
            Thread.sleep(1000);
            mRtcStreamingManager.startConference(userId, roomId, roomToken, new RTCStartConferenceCallback() {
                @Override
                public void onStartConferenceSuccess() {

                        mAudioCapturer.setOnAudioFrameCapturedListener(new AudioCapturer.OnAudioFrameCapturedListener() {
                            @Override
                            public void onAudioFrameCaptured(byte[] audioData, long ts) {
                                if (audioData != null) {
                                    int length = audioData.length;
                                    mRtcStreamingManager.inputAudioFrame(audioData, ts);
                                } else {
                                    showToast("音频数据为空!");
                                }
                            }
                        });


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast(getString(R.string.add_audio));
                            mProgressDialog.dismiss();
                        }
                    });

                }

                @Override
                public void onStartConferenceFailed(final int errorCode) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast(getString(R.string.failed_to_start_conference) + errorCode);
                            mProgressDialog.dismiss();
                        }
                    });
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void showToast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        mAudioCapturer.startCapture();
        if (mAudioCapturer != null) {
            mAudioCapturer.setOnAudioFrameCapturedListener(mOnAudioFrameCapturedListener);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        mRtcStreamingManager.stopConference();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRtcStreamingManager.destroy();
        RTCStreamingManager.deinit();
    }

    private AudioCapturer.OnAudioFrameCapturedListener mOnAudioFrameCapturedListener = new AudioCapturer.OnAudioFrameCapturedListener() {
        @Override
        public void onAudioFrameCaptured(byte[] audioData, long ts) {
            mRtcStreamingManager.inputAudioFrame(audioData, ts);
        }
    };

    private final AtomicBoolean isStreamingStared = new AtomicBoolean(false);

}
